import { legacy_createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import "../api/data"
import { ALLACTION, ALLSTATE, GETLIST, GETSHOPCAR,} from "../types/store.d"
const initialState = {
    imgsArr: JSON.parse(window.localStorage.getItem('imgsArr') as string) || [],
    listArr: JSON.parse(window.localStorage.getItem('listArr') as string) || [],
    classifyArr: JSON.parse(window.localStorage.getItem('classifyArr') as string) || [],
    shopcarArr: JSON.parse(window.localStorage.getItem('shopcarArr') as string) || [],
    rightArr: JSON.parse(window.localStorage.getItem('rightArr') as string) || [],
    addressArr: []
}

const reducer = (state: ALLSTATE = initialState, { type, payload }: ALLACTION) => {
    switch (type) {
        case GETLIST:
            let Arr = [...state.listArr]
            Arr = payload;
            state.listArr = Arr;
            window.localStorage.setItem('listArr', JSON.stringify(state.listArr))
            return { ...state }
        case GETSHOPCAR:
            let arr = [...state.shopcarArr]
            let isFlag = arr.some((item, index) => {
                return item.id === payload.id
            })
            if (isFlag) {
                arr.forEach((item, index) => {
                    if (item.id === payload.id) {
                        item.num++
                    }
                })
            } else {
                payload.num = 1;
                payload.flag = false;
            }
            arr.push(payload);
            state.shopcarArr = arr;
            window.localStorage.setItem('shopcarArr', JSON.stringify(state.shopcarArr))
            return { ...state }
        default:
            return state
    }
}


const store = legacy_createStore(reducer, applyMiddleware(thunk, logger))
export default store;